package com.ibm.cloud.envcheck.basicservice;

import java.io.File;
import java.io.FileOutputStream;

import com.ibm.cloud.envcheck.bean.CopyRemoteFileToLocalParam;
import com.ibm.cloud.envcheck.service.RemoteBasicService;
import com.ibm.cloud.envcheck.service.type.ServiceType;

public class RemoteCheckConfigFile  extends RemoteBasicService<CopyRemoteFileToLocalParam>{
	@Override
	public int getCode() {
		
		return ServiceType.REMOTE_CONFIG_CONF.getCode();
	}

	@Override
	public void handle(CopyRemoteFileToLocalParam param) {
		initChannel(param);
		try {
			byte[] buf = new byte[1024];
			// send '\0'
			buf[0] = 0;
			out.write(buf, 0, 1);
			out.flush();
			while (true) {
				int c = checkAck(in);
				if (c != 'C') {
					break;
				}
				// read '0644 '
				in.read(buf, 0, 5);
				long filesize = 0L;
				while (true) {
					if (in.read(buf, 0, 1) < 0) {
						// error
						break;
					}
					if (buf[0] == ' ')
						break;
					filesize = filesize * 10L + (long) (buf[0] - '0');
				}
				String file = null;
				for (int i = 0;; i++) {
					in.read(buf, i, 1);
					if (buf[i] == (byte) 0x0a) {
						file = new String(buf, 0, i);
						break;
					}
				}

				String prefix = null;
				if (new File(param.getLocalDirectory()).isDirectory()) {
					prefix = param.getLocalDirectory() + File.separator;
				}
				buf[0] = 0;
				out.write(buf, 0, 1);
				out.flush();

				// read a content of lfile
				fos = new FileOutputStream(prefix == null ? param.getLocalDirectory() : prefix + file);
				int foo;
				while (true) {
					if (buf.length < filesize)
						foo = buf.length;
					else
						foo = (int) filesize;
					foo = in.read(buf, 0, foo);
					if (foo < 0) {
						// error
						break;
					}
					fos.write(buf, 0, foo);
					filesize -= foo;
					if (filesize == 0L)
						break;
				}
				fos.close();
				fos = null;
				if (checkAck(in) != 0) {
					//System.exit(0);
					in.close();
					return;
				}
				// send '\0'
				buf[0] = 0;
				out.write(buf, 0, 1);
				out.flush();
				//System.exit(0);
				out.close();
				
			}
		} catch (Exception e) {
		}
		destroy();
	
	}
}
